Convert HTML to MS Word file using PHP and custom library

convert-html-content-to-ms-word-file-using-php

The export functionality to the document on the server is extremely useful for converting HTML content to MS word document and download it as a.docx file. The MS word document can be quickly generated with HTML content via PHP.

Converting HTML to MS Word Document used primarily in the web application to generate.doc/.docx file with dynamic HTML data. The most popular file format is the Microsoft word document for exporting dynamic content offline. The JavaScript can be easily used to export HTML content to MS Word functionality. However, if you want to convert dynamic content to Doc, the interaction on the server-side is required. In this tutorial, we will show you step by step process to convert HTML to MS word file using PHP.

Step-1: Create html_to_doc.php file

In the html_to_doc.php file, we will write a custom class library code that helps to generate MS Word file and include the HTML content in Word document using PHP.

In the above code,

  • setDocFileName() – Set document file name.
  • setTitle() – Set document title.
  • getHeader() – Create header section of the document.
  • getFotter() – Create footer section of the document.
  • createDoc() – Create word document in .dcox format.
  • _parseHtml() – Parse and filter HTML from source.
  • write_file() – Insert content in the word file.

Step-2: Create index.php file

Copy and paste the following code in the index.php file. Here we will load the html_to_doc.php library and initialize the class. After this, we will specify custom HTML content to convert into Word document. Call the createDoc() function to convert HTML content to Word document.

If you want to automatically download word file:

To download the word file, set the third parameter of the createDoc() to TRUE.

Generate Word document from HTML File:

You can convert the contents of the HTML file to a Word document by specifying the HTML file name.

How to Convert an Image to PDF in CodeIgniter using FPDF Library

How to Generate PDF with Watermark in PHP using Dompdf

Related posts